import {messages} from "share/common";
import React from 'react';
import { DatePicker, Select, Row, Col } from 'antd';
const Option = Select.Option;
const { RangePicker } = DatePicker;
import moment from 'moment'
class DateCombined extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      value: null, //{startDate: '', endDate: '', duration: 0}
      maxDuration: 0,
      duration: null,
      dateRange: []
    };
  }

  componentWillMount() {
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this)
      }
  }

  componentDidMount() {
    if(this.props.onRef) {
      this.props.onRef(this)
    }
  }

  componentDidMount() {
    if(this.props.onRef) {
      this.props.onRef(this)
    }
  }

  componentWillReceiveProps(nextProps){
    if(nextProps.value){
      try {
        let valueWillSet = JSON.parse(nextProps.value);
        let maxDuration = moment(valueWillSet.endDate).subtract('-1','days').utc().diff(moment(valueWillSet.startDate).utc(), 'days');
        this.setState({
          value: valueWillSet,
          //fix bug25185 时间显示错误
          dateRange: [
            moment(valueWillSet.startDate),
            moment(valueWillSet.endDate)
          ],
          duration: valueWillSet.duration,
          maxDuration
        })
      } catch(e) {}
    } else {
      this.setState({
        maxDuration: 0,
        value: null,
        dateRange: [],
        duration: null
      })
    }
  }

  onChange = (changedValue) => {
    const onChange = this.props.onChange;
    if (onChange) {
      onChange(changedValue);
    }
  };

  onChangeDate = (dates) => {
    console.log(dates,'dates');
    const { isNeedTime } = this.props;
    let formData = isNeedTime ? 'YYYY-MM-DD HH:mm' : 'YYYY-MM-DD';
    if(dates.length === 2){
      let duration = dates[1].diff(dates[0], 'days');
      // 需求4140：费用开始结束日期控件计算逻辑配置
      if (this.props.daysComputeMode === 2) duration++;
      let value = {
        startDate: moment(dates[0].format(formData)).utc(),
        endDate: moment(dates[1].format(formData)).utc(),
        duration
      };
      this.setState({ dateRange: dates, duration, value, maxDuration: duration });
      this.onChange(JSON.stringify(value))
    } else {
      this.setState({
        maxDuration: 0,
        value: null,
        dateRange: [],
        duration: null
      });
      this.onChange(null)
    }
  };

  onChangeDuration = (duration) => {
    const { dateRange } = this.state;
    let value = {
      startDate: dateRange ? dateRange[0].utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z' : null,
      endDate: dateRange ? dateRange[1].utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z' : null,
      duration
    };
    this.setState({duration, value});
    this.onChange(JSON.stringify(value))
  };

  render() {
    const { duration, dateRange, maxDuration } = this.state;
    const { disabled, isSubsidyType, isNeedTime } = this.props;
    let options = [];
    for(let count = 0; count < (this.props.daysComputeMode === 2 ? maxDuration + 1 : maxDuration); count++){
      options.push(count);
    }
    return (
      <div>
        <RangePicker onChange={this.onChangeDate}
                     value={dateRange}
                     disabled={disabled || isSubsidyType} //fix bug 25357
                     placeholder={[messages('my-account.key13'/*开始日期*/), messages('my-account.key14'/*结束日期*/)]}
                     format={isNeedTime ? "YYYY-MM-DD HH:mm" : "YYYY-MM-DD"}
                     style={{ width: '100%' }}/>
        <Row gutter={20} style={{ marginTop: 12, display: 'none' }}>
          <Col span={16}>
            <Select value={duration ? Number(duration) : duration}
                    placeholder={messages('common.please.select')}
                    disabled={dateRange.length === 0 || disabled || isSubsidyType}
                    onChange={this.onChangeDuration} style={{ width: '100%' }}>
              {options.map(item => {
                return <Option key={item} value={item}>{messages('my-account.key148',{arg1: item}/*总计{arg1}天*/)}</Option>
              })}
            </Select>
          </Col>
        </Row>
      </div>
    );
  }
}

DateCombined.PropTypes = {
  onRef:React.PropTypes.func,
  onChange: React.PropTypes.func,  //进行选择后的回调
  value: React.PropTypes.string,  //值
  disabled: React.PropTypes.bool,  //是否可编辑
  isSubsidyType: React.PropTypes.bool,  //是否为差补费用
  daysComputeMode: React.PropTypes.number, //总天数计算逻辑：1（结束日期-开始日期）、2（结束日期-开始日期+1）
  isNeedTime: React.PropTypes.bool
};

DateCombined.defaultProps = {
  disabled: false,
  isSubsidyType: false,
  isNeedTime: false
};

DateCombined.defaultProps = {};

export default DateCombined;
